package com.example.android.jmatt.acc;

import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Iterator;

import android.app.Activity;
import android.content.res.ColorStateList;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Debug;
import android.os.SystemClock;
import android.text.Spannable;
import android.text.style.TextAppearanceSpan;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

public class AppyActivity extends Activity {
    /** Called when the activity is first created. */
    
    private TextAppearanceSpan[] colors;
    private boolean mFirstRead = false;
    private static final String DELIMITER = " -- ";
    private ArrayList<Double> mTimes = new ArrayList<Double>();
    private int scaleDivisor = 900;
    
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        configureUi();
    }
    

    @Override
    protected void onResume() {
        super.onResume();
        //Debug.startMethodTracing("/sdcard/trace_" + System.currentTimeMillis() % 1000000);
    }

    private void configureUi() {
        ((Button) findViewById(R.id.button)).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                readNextFile();
            }
        });

        ((Button) findViewById(R.id.button)).setOnTouchListener(new View.OnTouchListener() {

            @Override
            public boolean onTouch(View v, MotionEvent event) {
                if (event.getAction() == MotionEvent.ACTION_UP) {
                    Job j = new Job();
                    j.startTime = event.getEventTime();
                    mJobs.add(j);
                    AppyActivity.this.findViewById(R.id.layout_parent).setBackgroundColor(0xFFFF0000);
                }
                return false;
            }
            
        });
        
        TextAppearanceSpan blue = new TextAppearanceSpan("Droid Sans",
                android.R.style.TextAppearance_Medium, 30, 
                getResources().getColorStateList(R.color.blue), null);
        TextAppearanceSpan red = new TextAppearanceSpan("Droid Sans",
                android.R.style.TextAppearance_Medium, 30, 
                getResources().getColorStateList(R.color.red), null);
        TextAppearanceSpan yellow = new TextAppearanceSpan("Droid Sans",
                android.R.style.TextAppearance_Medium, 30, 
                getResources().getColorStateList(R.color.yellow), null);
        TextAppearanceSpan green = new TextAppearanceSpan("Droid Sans",
                android.R.style.TextAppearance_Medium, 30, 
                getResources().getColorStateList(R.color.green), null);
        colors = new TextAppearanceSpan[] {blue, red, yellow, blue, green, red};
        styleText();

    }
    
    private ArrayList<Job> mJobs = new ArrayList<Job>();
    
    private int mDispatchedCount = 0;
    
    private void readNextFile() {
        TextView tv = (TextView) (findViewById(R.id.text_box));
        if (!mFirstRead) {
            tv.setText("");
            mTimes.clear();
            Job real = mJobs.get(mJobs.size() - 1);
            mJobs.clear();
            mJobs.add(real);
        }
        InputStream incoming = FileReaderFactory.getNextStream();
        
        ReaderUpdateListener readMonitor = new ReaderUpdateListener();
        FileReaderTask reader = new FileReaderTask(readMonitor);
        
        (new PointlessTask()).execute(null);
        
        mJobs.get(mDispatchedCount).stream = incoming;
        reader.execute(mJobs.get(mDispatchedCount));
        mDispatchedCount++;
        mFirstRead = true;
        
        if (mJobs.size() == mDispatchedCount) {
            findViewById(R.id.layout_parent).setBackgroundColor(0xFF000000);
        }
    }
    
    private void styleText() {
        Spannable styledText = (Spannable) ((TextView) findViewById(R.id.text_box)).getText();
        String text = styledText.toString();
        String[] words;
        if (!mFirstRead) {
            words = text.split(" ");
            Job dummy = new Job();
            dummy.startTime = 0;
            dummy.finishTime = scaleDivisor;
            for (int count = 0; count < words.length; count++) {
                mJobs.add(dummy);
            }
        } else {
            words = text.split(DELIMITER);
        }
        
        int position = 0;
        Iterator<Job> timeTraveler = mJobs.iterator();
        for (int count = 0; count < words.length; count++) {
            TextAppearanceSpan source = colors[count % colors.length];
            Job j = timeTraveler.next();
            double textScale = (j.finishTime - j.startTime) / (double) scaleDivisor;
            
            TextAppearanceSpan thisOne = new TextAppearanceSpan(source.getFamily(),
                    source.getTextStyle(), 
                    (new Double(source.getTextSize() * textScale)).intValue(),
                    source.getTextColor(), source.getLinkTextColor());
            styledText.setSpan(thisOne, position, position + words[count].length(), 0);
            position += (words[count].length() + (mFirstRead ? DELIMITER.length() : 1));
        }
    }

    @Override
    protected void onPause() {
        super.onPause();
        //Debug.stopMethodTracing();
    }
    
    
    private void drawText() {
        StringBuilder sb = new StringBuilder();
        for (Job j : mJobs) {
            if (j.finishTime != -1) {
                long totalTime = j.finishTime - j.startTime;
                sb.append("Delay time: " + totalTime + "ms for " + 
                    (j.bytes.length/1024) + " KB"  + DELIMITER);
            } else {
                sb.append("Waiting...");
            }
        }
        ((TextView) findViewById(R.id.text_box)).setText(sb.toString());
    }
    
    private class ReaderUpdateListener implements FileReaderTask.ProgressListener {
        
        @Override
        public void onProgress(Integer progress) {
            
        }

        @Override
        public void onFinished(Job job) {
            drawText();
            styleText();
        }
    }
    
    private class PointlessTask extends AsyncTask<Void, Void, Void> {

        @Override
        protected Void doInBackground(Void... arg0) {
            try {
                Thread.sleep(20000);
            } catch (InterruptedException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            return null;
        }
        
    }
}